<template>
  <div class="gifts-container">
    <div class="page-header">
      <h2>礼品管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        创建礼品
      </el-button>
    </div>

    <el-card>
      <el-table
        v-loading="loading"
        :data="gifts"
        style="width: 100%"
      >
        <el-table-column prop="name" label="礼品名称" min-width="150" />
        <el-table-column prop="points_required" label="所需积分" width="100">
          <template #default="{ row }">
            <el-tag type="warning">{{ row.points_required }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100">
          <template #default="{ row }">
            {{ row.stock === -1 ? '不限量' : row.stock }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="兑换时间" width="300">
          <template #default="{ row }">
            <div>{{ formatDateTime(row.start_time) }}</div>
            <div>{{ row.end_time ? formatDateTime(row.end_time) : '永久有效' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="物流" width="100">
          <template #default="{ row }">
            <el-tag :type="row.need_shipping ? 'primary' : 'info'">
              {{ row.need_shipping ? '实物' : '虚拟' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort_order" label="排序" width="80" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                type="primary"
                link
                @click="handleEdit(row)"
              >
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button
                type="danger"
                link
                @click="handleDelete(row)"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑礼品' : '创建礼品'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="礼品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入礼品名称" />
        </el-form-item>

        <el-form-item label="礼品描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入礼品描述"
          />
        </el-form-item>

        <el-form-item label="所需积分" prop="points_required">
          <el-input-number
            v-model="form.points_required"
            :min="1"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="库存" prop="stock">
          <el-input-number
            v-model="form.stock"
            :min="-1"
            style="width: 100%"
          />
          <div class="form-tip">-1表示不限量，0表示已下架</div>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="兑换时间" prop="start_time">
          <el-date-picker
            v-model="form.start_time"
            type="datetime"
            placeholder="请选择开始时间"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="结束时间" prop="end_time">
          <el-date-picker
            v-model="form.end_time"
            type="datetime"
            placeholder="请选择结束时间（可选）"
            style="width: 100%"
          />
          <div class="form-tip">不设置表示永久有效</div>
        </el-form-item>

        <el-form-item label="排序权重" prop="sort_order">
          <el-input-number
            v-model="form.sort_order"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="物流" prop="need_shipping">
          <el-switch
            v-model="form.need_shipping"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import request from '../../utils/request'

const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const gifts = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const formRef = ref(null)

const form = reactive({
  id: null,
  name: '',
  description: '',
  points_required: 1,
  stock: -1,
  status: 1,
  start_time: '',
  end_time: null,
  sort_order: 99,
  need_shipping: 0
})

const rules = {
  name: [
    { required: true, message: '请输入礼品名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入礼品描述', trigger: 'blur' }
  ],
  points_required: [
    { required: true, message: '请输入所需积分', trigger: 'blur' },
    { type: 'number', min: 1, message: '积分必须大于等于1', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  start_time: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  sort_order: [
    { required: true, message: '请输入排序权重', trigger: 'blur' }
  ]
}

const fetchGifts = async () => {
  loading.value = true
  try {
    const response = await request.get('/gifts', {
      params: {
        page: currentPage.value,
        per_page: pageSize.value
      }
    })
    gifts.value = response.data.data
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('获取礼品列表失败')
  } finally {
    loading.value = false
  }
}

const formatDateTime = (datetime) => {
  return new Date(datetime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.id = null
  form.name = ''
  form.description = ''
  form.points_required = 1
  form.stock = -1
  form.status = 1
  form.start_time = ''
  form.end_time = null
  form.sort_order = 99
  form.need_shipping = 0
}

const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (gift) => {
  isEdit.value = true
  Object.assign(form, gift)
  dialogVisible.value = true
}

const handleDelete = async (gift) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个礼品吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await request.delete(`/gifts/${gift.id}`)
    ElMessage.success('删除成功')
    fetchGifts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (isEdit.value) {
      await request.put(`/gifts/${form.id}`, form)
      ElMessage.success('修改成功')
    } else {
      await request.post('/gifts', form)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    fetchGifts()
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('操作失败')
    }
  } finally {
    submitting.value = false
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchGifts()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchGifts()
}

onMounted(() => {
  fetchGifts()
})
</script>

<style scoped>
.gifts-container {
  padding: 1rem;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.page-header h2 {
  margin: 0;
  font-size: 1.5rem;
  color: var(--dark-color);
}

.pagination-container {
  margin-top: 1.5rem;
  display: flex;
  justify-content: flex-end;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}
</style> 